package com.piggy.mq.scan;

import com.piggy.mq.annotation.ScanMQBean;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ClassUtils;

import static cn.hutool.extra.spring.SpringUtil.getApplicationContext;

public class ScanMQBeanPackage {

    public static String[] scanPackage() {
        String[] basePackages = null;

        ApplicationContext context = getApplicationContext();
        String[] enableWebSocketBeanNames = context.getBeanNamesForAnnotation(ScanMQBean.class);
        if (enableWebSocketBeanNames.length != 0) {
            for (String enableMQBeanName : enableWebSocketBeanNames) {
                Object enableMQBean = context.getBean(enableMQBeanName);
                ScanMQBean enableMQ = AnnotationUtils.findAnnotation(enableMQBean.getClass(), ScanMQBean.class);
                assert enableMQ != null;
                if (enableMQ.scanBasePackages().length != 0) {
                    basePackages = enableMQ.scanBasePackages();
                    break;
                }
            }
        }

        // use @SpringBootApplication package
        if (basePackages == null) {
            String[] springBootApplicationBeanName = context.getBeanNamesForAnnotation(SpringBootApplication.class);
            Object springBootApplicationBean = context.getBean(springBootApplicationBeanName[0]);
            SpringBootApplication springBootApplication = AnnotationUtils.findAnnotation(springBootApplicationBean.getClass(), SpringBootApplication.class);
            assert springBootApplication != null;
            if (springBootApplication.scanBasePackages().length != 0) {
                basePackages = springBootApplication.scanBasePackages();
            } else {
                String packageName = ClassUtils.getPackageName(springBootApplicationBean.getClass().getName());
                basePackages = new String[1];
                basePackages[0] = packageName;
            }
        }

        /*MQClassPathScanner scanHandle = new MQClassPathScanner((BeanDefinitionRegistry) context, false);
        if (resourceLoader != null) {
            scanHandle.setResourceLoader(resourceLoader);
        }

        for (String basePackage : basePackages) {
            scanHandle.doScan(basePackage);
        }*/
       return basePackages;

    }

}
